<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui/css/layui.css" media="all">
    <script type="text/javascript" src="../../../res/js/jquery-3.4.1.min.js"></script>
    <style>
        .divbu {
            height: 500PX;
            white-space: nowrap;
            float: left;
            overflow-y: auto;
        }
        #myform{
            position: relative;
            top: 15px;
        }

    </style>
</head>

<body>

<form class="layui-form" action="" method="post" lay-filter="myform" id="myform">
    <div class="layui-form-item">

<!--        <div class="layui-inline">-->
<!--            <label class="layui-form-label">店名：</label>-->
<!--            <div class="layui-input-inline">-->
<!--                <select id="immName">-->
<!--                    <option value="">-&#45;&#45;请选择店名</option>-->
<!--                </select>-->
<!--            </div>-->
<!--        </div>-->

        <div class="layui-inline" id="drugN">
            <label class="layui-form-label">药品名称：</label>
            <div class="layui-input-inline">
                <input type="text" name="drugName" id="drugName" placeholder="药品名称" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-inline" id="btn">
            <div class="layui-input-inline">
                <button type="button" class="layui-btn" lay-submit="" onclick="query()">搜索</button>
            </div>
        </div>



    </div>
</form>

<script type="text/html" id="toolbarDemo2">

</script>

<div style="width: 100%" class="divbu">
    <table class="layui-hide" class="list" id="test" lay-filter="test"></table>
</div>
<div style="width: 99%" class="divbu">
    <table class="layui-hide" id="test1" lay-filter="test1"></table>
    <button class="layui-btn layui-btn-sm" id="getData" style="">保存</button>
</div>
<input type="hidden" id="sellId" name="sellId">

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <!--<button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>-->
    </div>
</script>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-xs" lay-event="addDrug">药品操作</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script type="text/html" id="barDemo1">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!--显示图片-->
<script type="text/html" id="img">
    <img src="{{d.images}}" width="50" height="50" onclick="showBig(this)"/>
</script>

<script type="text/html" id="input">
    <div class="layui-inline">
        <input class="layui-input" maxlength="8" style="border:none;padding-bottom:8px;" name="detailCount" id="{{d.detailCount}}" autocomplete="off" placeholder="输入药品数量" value="{{d.detailCount}}" onblur="clearNoNum(this);">
    </div>
</script>

<script src="../../../res/layui/layui.js" charset="utf-8"></script>
<script>

    var openIndex = null;
    var table = null;
    var array = new Array();
    var test1Data = [];
    var eleTree = null;
    layui.config({
        base: "../../lib/layui/lay/mymodules/"
    })
    layui.use(['table', 'layer','eleTree','form'], function () {
        table = layui.table;
        form = layui.form;
        eleTree = layui.eleTree;
        var ids = [];
        getData();
        table.render({
            elem: '#test'
            , url: '../../../hqDrug/selectAlls'
            //, toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            /*, defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
                title: '提示'
                , layEvent: 'LAYTABLE_TIPS'
                , icon: 'layui-icon-tips'
            }]*/
            , title: '用户数据表'
            , cols: [[
                {type: 'checkbox',LAY_CHECKED:false,fixed: 'left'}
                , {field: 'typeName', title: '类型', width: 120}
                , {field: 'drugName', title: '药品名称', width: 120}
                // , {field: 'alias', title: '别名', width: 100}
                , {field: 'drugRetail', title: '零售价', width: 150}
                , {field: 'drugWho', title: '批发价', width: 150}
                // , {field: 'drugOut', title: '分店价', width: 100}
                // , {field: 'drugExp', title: '药品说明', width: 150}
                // , {field: 'taboo', title: '主要用药禁忌', width: 120}
                , {field: 'count', title: '数量', width: 80}
                , {field: 'images', title: '药品图片', width: 100, templet:'#img'}
                // , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 220}
            ]]
            , page: true
            , id:'test'
            , parseData: function (res) {//res 即为原始返回的数据
                ids = res.data;
                for(var i in res.data){
                    for(var j=0;j<array.length;j++){
                        if(array[j].drugId==res.data[i].drugId){

                            //如果set集合中有的话，给rows添加check属性选中
                            res.data[i]["LAY_CHECKED"] = true;
                        }
                    }
                }

                return {
                    "code": res.code, //解析接口状态
                    "count": res.count, //解析数据长度
                    "data": res.data //解析数据列表
                };
            }
        });
        //查询药店
        // var url="../../../hqImm/queryImmName";
        // $.post(url,null,function (obj) {
        //     $.each(obj,function (index,item) {
        //         $("#immName").append("<option value='"+item.immId+"'>"+item.immName+"</option>");
        //     })
        //     form.render("select");
        // },"json")

        table.on('checkbox(test)', function(obj){
            var checkStatus = table.checkStatus('test');
            var data = checkStatus.data;

            if(obj.type=="all"){

                if(data.length==0){
                    console.info(ids);
                    for(var i = 0;i<ids.length;i++){
                        for(var j=0;j<array.length;j++){
                            if(ids[i].drugId==array[j].drugId ){
                                array.splice(j,1)
                            }
                        }
                    }
                }else{
                    $.each(data,function (index,item) {
                        if(JSON.stringify(array).indexOf(JSON.stringify(item.drugId))<0){
                            item.detailCount=1;
                            item.sellId = $("#sellId").val();
                            array.push(item)
                        }
                    })
                }
            }else{
                if(!obj.checked){
                    for(var i=0;i<array.length;i++){
                        if(JSON.stringify(obj.data.drugId)==JSON.stringify(array[i].drugId)){
                            array.splice(i,1);
                            break;
                        }
                    }
                }else{
                    $.each(data,function (index,item) {
                        if(JSON.stringify(array).indexOf(JSON.stringify(item.drugId))<0){
                            item.sellId = $("#sellId").val();
                            item.detailCount=1;
                            array.push(item)
                            console.info(item);
                        }
                    })
                }
            }

            refresh(array);
        });

        $("#getData").on('click',function(){
            var url = "../../../sellDetail/inserts";
            // var data = table.cache['test1'];
            // var data = test1Data;
            var loa ;

            // if($("#immName").val() == "" || $.trim($("#immName").val()).length == 0){
            //     layer.msg("请选择分店！");
            // }else{
                if(array.length>0){
                    $.ajax({
                        url:url,
                        data:{ wl: JSON.stringify(array)}, //,immName:$("#immName").val()
                        type:"post",
                        dataType:"json",
                        traditional:true,
                        beforeSend:function(){
                            loa = layer.load(0,{shade:true,time: 2*1000});
                        },
                        success:function (obj) {
                            layer.msg(obj.message)
                            if (obj.status == 20) {
                                layer.close(loa);
                                parent.layui.table.reload("testReload");
                                //关闭当前弹出层
                                parent.closeOpen(obj.message);
                            }
                        }
                    })
                }else{
                    layer.message("请选择计划生产的药品");
                }
            // }

        })

        table.on('edit(test1)', function(obj){ //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
            var dd = obj.value.replace(/[^\d]/g,"");  //清除“数字”和“.”以外的字符

            if(dd == ""){
                dd =1;
            }else if(dd.indexOf("0")==0){
                dd = dd.substring(1,dd.length);
            }

            for(var i=0;i<array.length;i++){
                if(array[i].drugId==obj.data.drugId){
                    array[i].detailCount = dd;
                    array[i].count = dd;
                }
            }

            refresh(array);
        });


        //头工具栏事件
        table.on('toolbar(test1)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            switch (obj.event) {
                case 'submit':
                    break;
                case 'getCheckLength':
                    var data = checkStatus.data;
                    layer.msg('选中了：' + data.length + ' 个');
                    break;
                case 'addRec':
                    //页面层
                    openIndex = layer.open({
                        type: 2,
                        skin: 'layui-layer-rim', //加上边框
                        maxmin: true,
                        area: ['50%', '65%'], //宽高
                        content: 'addOrUpdate.html'
                    })
                    break;

                //自定义头工具栏右侧图标 - 提示
                case 'LAYTABLE_TIPS':
                    layer.alert('这是工具栏右侧自定义的一个图标按钮');
                    break;

            };
        });

        //监听行工具事件
        table.on('tool(test1)', function (obj) {
            var data = obj.data;
            if(obj.event==='del'){
                layer.confirm('真的删除行么', function (index) {
                    for(var i =0 ;i<array.length;i++){
                        if(array[i].drugId==data.drugId){
                            array.splice(i,1);
                            refresh(array);
                            table.reload("test")
                            break;
                        }

                    }

                    layer.close(index);
                });
            }
        })

        //监听行工具事件
        table.on('tool(test)', function (obj) {
            var data = obj.data;
        });


    });

    function query() {
        table.reload('test',{
            where:{
                drugName:$("#drugName").val()
            },
            page:{
                curr:1
            }
        })

    }

    /**
     * 关闭层
     */
    function closeOpen(msg) {
        layer.close(openIndex);
        layer.msg(msg, {time: 1000}, function () {
            table.reload("test");//刷新表格
        })
    }

    /**
     * 获取已有的生成计划详情
     */
    function getData(){
        $.ajax({
            url:"../../../hqPdetail/selectOne",
            type:"get",
            data:{sellId:$("#sellId").val()},
            dataType: "json",
            async:false,
            success:function (obj) {
                $.each(obj,function (index,item) {
                    array.push(item);
                })
                refresh(array);
            }
        })
    }


    /**
     * 图片
     */
    function showBig(obj) {
        $("#imgDiv").fadeToggle(1000);
        $("#imgDiv_img").prop("src", obj.src)
    }


    function refresh(obj){
        table.render({
            elem: '#test1'
            , data: obj
            // , defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
            //     title: '提示'
            //     , layEvent: 'LAYTABLE_TIPS'
            //     , icon: 'layui-icon-tips'
            // }]
            , title: '用户数据表'
            ,limit:obj.length
            , toolbar: '#toolbarDemo2' //开启头部工具栏，并为其绑定左侧模板
            , cols: [[
                {field: 'typeName', title: '类型', width: '10%'}
                , {field: 'drugName', title: '药品名称', width: '10%'}
                , {field: 'detailCount', title: '数量', width: '10%', edit:'test'}
                // , {field: 'remark', title: '备注', width: '20%', edit:'test'}
                , {fixed: 'right', title: '操作', toolbar: '#barDemo1', width: '50%'}
            ]]
            ,done: function(res){
                test1Data = res.data;
            }
        });

    }

</script>
<div id="imgDiv" style="display:none;position:absolute;left:20%;top:10%">
    <img src="" id="imgDiv_img" width="100%" height="100%" onclick="showBig(this)">
</div>
</body>
</html>